package com.skyline.feed.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.skyline.feed.dao.PersonalFeedDao;
import com.skyline.feed.model.FeedResult;
import com.skyline.feed.service.PersonalFeedService;
import com.skyline.feed.type.FeedType;
import com.skyline.wo.model.Article;

/**
 * 个人推信的实现
 * 
 * @author Jairus Chan
 * 
 */
@Service("personalFeedService")
public class PersonalFeedServiceImpl implements PersonalFeedService {

	@Autowired
	private PersonalFeedDao personalFeedDao;

	@Value("${feed.pagination.minPageSize}")
	private Integer MIN_PAGE_SIZE;

	@Value("${feed.personalFeed.maxFeedLevel}")
	private Integer MAX_FEED_LEVEL;

	@Override
	@Deprecated
	public void addFeed(Object resourceId, String title, String content, Long providerId, String providerNickname, String providerPortrait,
			Long ownerId, FeedType type) {
		personalFeedDao.insertFeed(resourceId, title, content, providerId, providerNickname, providerPortrait, ownerId, type);
	}

	@Override
	public void addArticleFeed(Article article) {
		personalFeedDao.insertFeed(article.getId(), article.getTitle(), article.getDigest(), article.getOwnerId(),
				article.getOwnerNickname(), article.getOwnerPortrait(), article.getOwnerId(), FeedType.ARTICLE);
	}

	@Override
	public FeedResult getFeeds(Long ownerId, Integer current, Integer level) {

		FeedResult result = new FeedResult();
		List<DBObject> resultData = new ArrayList<DBObject>();
		// 当返回推信数目小于MIN_PAGE_SIZE则会自动也去找下一级的personalFeed
		while (resultData.size() < MIN_PAGE_SIZE) {
			// 当找完了所有的personalFeed后，break；MAX_FEED_LEVEL表示最大的personalFeed的index;level
			// >= MAX_FEED_LEVEL意味找完了所有的personalFeed
			if (level > MAX_FEED_LEVEL) {
				break;
			}

			DBCursor cursor = personalFeedDao.queryFeeds(ownerId, current, level);

			// while(cursor.hasNext()){
			// resultData.add(cursor.next());
			// }
			List<DBObject> feeds = cursor.toArray();
			resultData.addAll(feeds);

			// 当返回推信数目小于MIN_PAGE_SIZE，则将currentPage置为0,并会自动也去找下一级的personalFeed
			if (resultData.size() < MIN_PAGE_SIZE) {
				current = 0;
				level = level + 1;
			} else {
				current = feeds.size();
			}
		}
		result.setCurrent(current);
		result.setData(resultData);
		result.setLevel(level);
		return result;
	}

	@Override
	public List<DBObject> getFeeds(List<Long> ownerIds, Integer level, Long lastQueryTime) {
		DBCursor cursor = personalFeedDao.queryFeeds(ownerIds, level, lastQueryTime);
		List<DBObject> objs = new ArrayList<DBObject>();
		while (cursor.hasNext()) {
			objs.add(cursor.next());
		}
		return objs;
	}

}
